import 'package:flutter/material.dart';
import '../../tool/keepAliveWrapper.dart';

class PageViewKeepAlive extends StatefulWidget {
  const PageViewKeepAlive({super.key});

  @override
  State<PageViewKeepAlive> createState() => _State();
}

class _State extends State<PageViewKeepAlive> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('PageViewKeepAlive')),
      body: PageView.builder(
        scrollDirection: Axis.vertical,
        itemCount: 10,
        itemBuilder: (context, index) =>
            KeepAliveWrapper(child: MyContainer(num: index)),
      ),
    );
  }
}

class MyContainer extends StatefulWidget {
  final int num;

  MyContainer({super.key, required this.num});

  @override
  State<MyContainer> createState() => _MyContainerState();
}

class _MyContainerState extends State<MyContainer> {
  @override
  Widget build(BuildContext context) {
    print("widget.num:${widget.num}"); // 打印当前屏的索引
    return Center(
      child: Text(
        '第${widget.num}屏',
        style: Theme.of(context).textTheme.titleLarge,
      ),
    );
  }
}
